package com.chat.api.websocket;


import com.chat.api.utils.util.DateUtil;
import net.sf.json.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;


@ServerEndpoint(value = "/websocket/{user}")
@Component
public class MyWebSocket {
    // 通过类似GET请求方式传递参数的方法（服务端采用第二种方法"WebSocketHandler"实现）
//    websocket = new WebSocket("ws://127.0.0.1:18080/testWebsocket?id=23&name=Lebron");
    /**
     * 在线人数
     */
    public static AtomicInteger onlineNumber = new AtomicInteger(0);

    /**
     * 所有的对象，每次连接建立，都会将我们自己定义的MyWebSocket存放到List中，
     */
    public static List<MyWebSocket> webSockets = new CopyOnWriteArrayList<MyWebSocket>();

    /**
     * 会话，与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 每个会话的用户
     */
    private String user;

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) throws IOException, EncodeException {
        if (user == null || "".equals(user)) {
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        onlineNumber.incrementAndGet();
        for (MyWebSocket myWebSocket : webSockets) {
            if (user.equals(myWebSocket.user)) {
                try {
                    session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return;
            }
        }
        this.session = session;
        this.user = user;
        webSockets.add(this);
        onlineList();
        sendMessage("<p><font color=\"#1e90ff\" >"+this.user + "：进入聊天室。。。</font></p>","connect");
        System.out.println("有新连接加入！ 当前在线人数" + onlineNumber.get());
    }

    public int getOnlineNumber(){
        return onlineNumber.get();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() throws IOException, EncodeException {
        onlineNumber.decrementAndGet();
//        sendMessage("<font color=\"#1e90ff\" >"+this.user + "：退出聊天室。。。</font>","close");
        webSockets.remove(this);
        System.out.println("有连接关闭！ 当前在线人数" + onlineNumber.get());
        onlineList();
    }

    /**
     * 在线人列表
     */
    public void onlineList() throws IOException, EncodeException {
        List<String> list = Lists.newArrayList();
        for (MyWebSocket webSocket : webSockets) {
            list.add(webSocket.user);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("message","1");
        map.put("data",list);
//        pushMessage(null,JSONObject.fromObject(map).toString(),null);
        for (MyWebSocket myWebSocket : webSockets) {
            myWebSocket.sendMessage(list.toString(),"online");
//            session.getAsyncRemote().sendText(JSONObject.fromObject(map).toString());
        }
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("user") String user) {
        System.out.println("来自" + user + "消息：" + message);
        pushMessage("<font color=\"#1e90ff\" >"+user +"</font>  "+ DateUtil.dateToStr(new Date(),12), message, null);
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message,String type) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (type.equals("online")){
                map.put("message", "1");
                map.put("data", message);
            }else if (type.equals("message")){
                map.put("message", "2");
                map.put("data", message);
//                System.out.println("消息已发送:" + message);
            }else  {
                map.put("message", "3");
                map.put("data", message);
                map.put("type",1);
            }
            session.getBasicRemote().sendText(JSONObject.fromObject(map).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息推送
     *
     * @param message
     * @param uuid    uuid为空则推送全部人员
     */
    public static void pushMessage(String user, String message, String uuid) {
        String trim = StringUtils.trim(message);
        if (StringUtils.isBlank(trim)){
            return;
        }
        if (uuid == null || "".equals(uuid)) {
            for (MyWebSocket myWebSocket : webSockets) {
                myWebSocket.sendMessage(user + ":" + message,"message");
            }
        } else {
            for (MyWebSocket myWebSocket : webSockets) {
                if (uuid.equals(myWebSocket.user)) {
                    System.out.println(myWebSocket.user);
                    myWebSocket.sendMessage(message,"message");
                }
            }
        }

    }
}

